<template>
	<div class="pagination">
		<button :class="{ prev: true, forbid: pageActive == 1 }" :disabled="pageActive == 1" @click="handlePrev">左</button>
		<div :class="{ btn: true, active: pageActive == 1 }" @click="handleItemClick(1)">
			{{ 1 }}
		</div>
		<template v-for="item in pagerCount" :key="item">
			<div v-if="item == 2 && pageActive > middleCount" class="btn">..</div>
			<div v-if="item == pagerCount" class="btn">...</div>
			<div v-else-if="item != 1" :class="{ btn: true, active: item == pageActive }" @click="handleItemClick(item)">
				{{ item }}
			</div>
		</template>
		<div v-if="pagerCount < pageTotal" :class="{ btn: true, active: 100 == pageActive }" @click="handleItemClick(100)">
			{{ pageTotal }}
		</div>
		<button
			:class="{ next: true, forbid: pageActive == pageTotal }"
			:disabled="pageActive == pageTotal"
			@click="handleNext"
		>
			右
		</button>
	</div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'

const props = defineProps({
	page: {
		type: Number,
		default: 10
	},
	total: {
		type: Number,
		default: 100
	}
})
const pagerCount = 7
const middleCount = 4
const pageActive = ref(1)
const pageTotal = ref(Number((props.total / props.page).toFixed(0)))
if (props.total % props.page) pageTotal.value++

watch(
	() => props.total,
	(newVal) => {
		pageTotal.value = Number((newVal / props.page).toFixed(0))
		if (newVal % props.page) pageTotal.value++
	}
)
function handleItemClick(item: any) {
	pageActive.value = item
}

function handlePrev() {
	pageActive.value--
}
function handleNext() {
	pageActive.value++
}
</script>

<style lang="less" scoped>
.pagination {
	display: flex;
	justify-content: flex-end;
	border: 1px solid red;
}
.prev,
.next {
	width: 35px;
	height: 35px;
	background: #fff;
	border-radius: 5px;
	border: none;
	outline: none;
	cursor: pointer;
}
.next {
	margin-left: 10px;
}
.forbid {
	cursor: not-allowed;
}
.btn {
	min-width: 35px;
	height: 35px;
	line-height: 35px;
	text-align: center;
	background: #fff;
	margin-left: 10px;
	border-radius: 5px;
	cursor: pointer;
}
.active {
	background: #539eee;
	color: #fff;
}
</style>
